# todo 这是笔记分类的视图
from flask import request
from marshmallow import ValidationError
from utils import ThreadLocal
from common.ApiResponse import ApiResponse
from common.ErrorCode import ErrorCode
from common.BaseResponse import BaseResponse
from models import db, Category
from .validate import AddCategorySchema, UpdateCategorySchema

add_category_schema = AddCategorySchema()
update_category_schema = UpdateCategorySchema()


# todo 分类添加
def add():
    data = request.get_json()
    print(f"data : {data}")
    try:
        # 尝试验证数据
        validated_data = add_category_schema.load(data)
        # 使用验证后的数据创建分类
        category = Category(
            category_name=data['categoryName'],
            category_alias=data['categoryAlias'],
            create_user=ThreadLocal.ThreadLocalUtil.get().get('id')
        )
        print(category)
        try:
            db.session.add(category)
            db.session.commit()
            return ApiResponse.success("添加分类成功")
        except Exception as e:
            db.session.rollback()  # 回滚事务
            # 记录异常信息到日志
            print(f"数据库操作失败: {str(e)}")
            error_response = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
            return ApiResponse.error(
                code=error_response.code,
                message=error_response.message
            )
    except ValidationError as err:
        print(f"err:{err.messages}")
        # 捕获验证错误，并返回错误响应
        # 将错误信息传递给客户端
        error_response = BaseResponse.from_error_code(ErrorCode.PARAMS_ERROR)
        first_key, first_value = next(iter(err.messages.items()))
        return ApiResponse.error(message=error_response.message, code=error_response.code,data=first_value[0])


# todo 分类列表视图
def Category_list():
    user_map = ThreadLocal.ThreadLocalUtil.get()
    category_list = db.session.query(Category).filter(Category.create_user == user_map.get('id')).all()
    data = []
    for category in category_list:
        data.append(
            {
                "id": category.id,
                "categoryName": category.category_name,
                "categoryAlias": category.category_alias,
                "createTime": category.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                "updateTime": category.update_time.strftime("%Y-%m-%d %H:%M:%S"),
            }
        )
    return ApiResponse.success(data=data)


# todo 分类详情视图
def detail():
    category_id = request.args.get("id")
    try:
        category = db.session.query(Category).filter(Category.id == category_id).first()
        data = {
            "id": category.id,
            "categoryName": category.category_name,
            "categoryAlias": category.category_alias,
            "createTime": category.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "updateTime": category.update_time.strftime("%Y-%m-%d %H:%M:%S"),
        }
        return ApiResponse.success(data=data)
    except Exception as e:
        error_response = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
        return ApiResponse.error(code=error_response.code, message=error_response.message,data="操作失败")


# todo 分类更新视图
def update():
    data = request.get_json()
    print(data)
    error = update_category_schema.validate(data)
    if error:
        error_response = BaseResponse.from_error_code(ErrorCode.PARAMS_ERROR)
        return ApiResponse.error(code=error_response.code, message=error_response.message)
    try:
        category = db.session.query(Category).filter(Category.id == data.get('id')).first()
        category.category_name = data.get('categoryName')
        category.category_alias = data.get('categoryAlias')
        db.session.commit()
        return ApiResponse.success("更新成功！")
    except Exception as e:
        error_response = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
        return ApiResponse.error(code=error_response.code, message=error_response.message,data="操作失败")


# todo 分类删除视图
def delete():
    category_id = request.args.get("id")
    try:
        category = db.session.query(Category).filter(Category.id == category_id).first()
        db.session.delete(category)
        db.session.commit()
        return ApiResponse.success("分类及其文章删除成功")
    except Exception as e:
        error_response = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
        return ApiResponse.error(code=error_response.code, message=error_response.message,data="操作失败")
